package com.sgb.kjwl.view.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import androidx.databinding.DataBindingUtil;

import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityWebBinding;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.utils.Constants;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.WebEvent;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import static com.sgb.kjwl.utils.Constants.POLICY_URL;


public class WebActivity extends AppActivity {
    private final String TAG = "WebView";
    private final String LOGIN_URL = "https://wapuser.gcw.net/home";
    private final String KEY = "waptoken";
    private static final String startKey = "startType";
    private static final String isStart = "isStartTimer";
    private ActivityWebBinding binding;
    private boolean fir = true;
    private LoginEntity loginEntity;
    private int type;
    private String isRegister;
    private String startType;
    private boolean isFirst = true;
    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, WebActivity.class);
        context.startActivity(intent);
    }
    public static void start(Context context,String url) {
        Intent intent = new Intent();
        intent.setClass(context, WebActivity.class);
        intent.putExtra("url",url);
        context.startActivity(intent);
    }

    public static void start(Activity context, int requestCode,String startType,String isStartTimer) {
        Intent intent = new Intent();
        intent.setClass(context, WebActivity.class);
        intent.putExtra(startKey,startType);
        intent.putExtra(isStart,isStartTimer);
        context.startActivityForResult(intent,requestCode);
    }

    @Override

    protected void setupActivityComponent(AppComponent appComponent) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        isRegister = getIntent().getStringExtra(isStart);
        startType = getIntent().getStringExtra(startKey);
        String url = getIntent().getStringExtra("url");
        if (!TextUtils.isEmpty(url)){
            setTitle(url);
            showWebView(url);
        }
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(WebActivity.this, R.layout.activity_web);
        binding.include.actionBarImageLeft.setVisibility(View.VISIBLE);
        binding.include.actionBarImageLeft.setOnClickListener(this);

        binding.webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
                handler.proceed();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return false;
            }


            @Override
            public void onPageFinished(WebView view, String url) {
                view.getSettings().setJavaScriptEnabled(true);
                super.onPageFinished(view, url);
                if (isFirst) {
                    if ("true".equals(isRegister)) {
                        setTimerButton(startType);
                    } else if ("false".equals(isRegister)) {
                        binding.bottomLayout.setVisibility(View.VISIBLE);
                        binding.tvPrivacy.setOnClickListener(WebActivity.this);
                        binding.bottomLayout.setEnabled(true);
                        binding.tvAgreement.setText("我已阅读并接受协议");
                        binding.tvAgreement.setOnClickListener(WebActivity.this);
                    }
                    isFirst = false;
                }
                if (type == EventConstant.EVENT_WEB_QRCODE) {
                    String title = view.getTitle();
                    if (!TextUtils.isEmpty(title)) {
                        binding.include.actionBarTitle.setText(title);
                    }
                }
                if (loginEntity == null) {
                    return;
                }
                String title = view.getTitle();
                if (!TextUtils.isEmpty(title)) {
                    binding.include.actionBarTitle.setText(title);
                }
                if (loginEntity != null) {
                    //原生登录成功之后调用JS方法
                    binding.webView.loadUrl("javascript:saveData('" + loginEntity.getToken() + "','" + LOGIN_URL + "','" + KEY + "')");
                }
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError
                    error) {
                super.onReceivedError(view, request, error);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    Log.i("详情页加载异常-----", request.getUrl() + "");
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    Log.i("详情页加载异常-----", error.getErrorCode() + "");
                }
            }

            // 这行代码一定加上否则效果不会出现

        });
    }

    @Override
    protected void init() {

    }

    private void showWebView(String link) {
        MLog.d(TAG, "link " + link);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                WebSettings webSettings = binding.webView.getSettings();

                if (Build.VERSION.SDK_INT >= 19) {
                    webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                }
                webSettings.setJavaScriptEnabled(true);
                webSettings.setDomStorageEnabled(true);
                webSettings.setAppCacheEnabled(true);
                binding.webView.loadUrl(link);
            }
        });

    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.action_bar_image_left:
                if (binding.webView.canGoBack() && !fir) {
                    binding.webView.goBack();//返回上个页面
                    return;
                } else {
                    finish();
                }
                break;
            case R.id.tv_agreement:
                Intent intent = new Intent();
                WebActivity.this.setResult(Activity.RESULT_OK, intent);
                WebActivity.this.finish();
                break;
            case R.id.tv_privacy:
                WebActivity.start(this,POLICY_URL);
                break;
            case R.id.tv_supplier:
                WebActivity.start(this,Constants.SUPPLIER_URL);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onWebEvent(WebEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_WEBVIEW) {
            type = 1;
            String link = (String) event.getMessageData();
            loginEntity = (LoginEntity) event.getObject();
            setTitle(link);
            showWebView(link);
            EventBus.getDefault().removeStickyEvent(event);
        }
        if (event.getMessageTag() == EventConstant.EVENT_WEB_FILE) {
            type = 2;
            DialogHelper.showProgressDialog(this, null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(true);
            String titile = (String) event.getMessageData();
            binding.include.actionBarTitle.setText(titile);
            showWebView("file:///android_asset/cause.html");
            DialogHelper.dismissProgressDialog();
        }
        if (event.getMessageTag() == EventConstant.EVENT_WEB_QRCODE) {
            type = 3;
            String link = (String) event.getMessageData();
            showWebView(link);
        }
    }

    private void setTitle(String link){
        if (Constants.LICENCE_URL.equals(link)) {
            binding.include.actionBarTitle.setText("经营帮用户协议");
        }else if (Constants.SUPPLIER_URL.equals(link)){
            binding.include.actionBarTitle.setText("经营帮企业认证协议");
        }else if (POLICY_URL.equals(link)){
            binding.include.actionBarTitle.setText("经营帮隐私协议");
        }
    }

    private void setTimerButton(String startType){
        binding.bottomLayout.setVisibility(View.VISIBLE);
        binding.tvAgreement.setVisibility(View.VISIBLE);
        if ("param2".equals(startType)){
            binding.tvSupplier.setVisibility(View.VISIBLE);
            binding.tvSupplier.setOnClickListener(this);
        }else {
            binding.tvSupplier.setVisibility(View.GONE);
        }
        binding.tvPrivacy.setOnClickListener(this);
        CountDownTimer timer = new CountDownTimer(6000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                String str = String.format("%1$ds点击阅读并接受协议", millisUntilFinished / 1000);
                binding.tvAgreement.setText(str);
            }

            @Override
            public void onFinish() {
                binding.bottomLayout.setEnabled(true);
                binding.tvAgreement.setText("我已阅读并接受协议");
                binding.tvAgreement.setBackgroundResource(R.drawable.bg);
                binding.tvAgreement.setOnClickListener(WebActivity.this);
            }
        };
        timer.start();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && binding.webView.canGoBack() && !fir) {
            binding.webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
